package cn.qingyun.gis.modules.enterprise.util;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author skb
 * @description: file工具类
 * @date 2024/1/9 15:13
 */
@Slf4j
public class FileTool {

    public static File transferToFile(MultipartFile multipartFile) {
        //选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file = FileUtil.createTempFile(filename[0], "." + filename[1], true);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            log.error("MultipartFile转File失败", e);
        }
        return file;
    }

    //将MultipartFile转化为File类的方法
    public static File MultipartFileToFile(MultipartFile multipartFile) {
        File toFile = null;
        try {
            if (!multipartFile.equals("") && !(multipartFile.getSize() <= 0)) {
                InputStream ins = multipartFile.getInputStream();
                toFile = new File(multipartFile.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            }
        } catch (IOException e) {
            log.error("MultipartFile转File失败", e);
        }
        return toFile;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除产生的临时文件的方法
    public static void deleteTempFile(File file) {
        if (file != null) {
            File delFile = new File(file.toURI());
            delFile.delete();
        }
    }
}
